package com.wang.bootbuilder.service;

import com.wang.bootbuilder.entity.param.CategoryParam;
import com.wang.bootbuilder.entity.pojo.Category;
import com.wang.bootbuilder.mapper.CategoryMapper;
import com.wang.bootbuilder.tools.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    @Qualifier(value = "customizeRedisTemplate")
    RedisTemplate redisTemplate;

    /*
    获取一级或某个二级分类列表
     */
    public JsonResult getCategoryList(Long parentId) {
        try {
            // 查询redis中是否有这个分类
            List<Category> categoryCacheList = (List<Category>) redisTemplate.opsForValue().get("srb:core:categoryList" + parentId);
            if (!CollectionUtils.isEmpty(categoryCacheList)) {
                return JsonResult.ok().data("categorys", categoryCacheList);
            }
        } catch (Exception e) {
            log.error("redis服务异常");
        }

        Map<String, Object> categoryMap = new HashMap<>();
        categoryMap.put("parent_id", parentId);
        List<Category> categoryList = categoryMapper.selectByMap(categoryMap);

        // 将查到的数据存入redis
        try {
            redisTemplate.opsForValue().set("srb:core:categoryList" + parentId, categoryList, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis服务异常");
        }

        return JsonResult.ok().data("categorys", categoryList);
    }

    /*
    添加分类
     */
    public JsonResult addCategory(CategoryParam param) {
        // 判断分类名是否已经存在
        if (!checkExisted(param.getCategoryName(), param.getParentId())) {
            return JsonResult.error().message("该分类名已经存在，请勿重复添加");
        }
        // 插入分类信息
        Category insertCategory = new Category();
        insertCategory.setCategoryName(param.getCategoryName());
        insertCategory.setParentId(param.getParentId());
        categoryMapper.insert(insertCategory);

        // 获取分类list
        Map<String, Object> categoryMap = new HashMap<>();
        categoryMap.put("parent_id", param.getParentId());
        List<Category> categoryList = categoryMapper.selectByMap(categoryMap);

        // 将查到的数据存入redis
        try {
            redisTemplate.opsForValue().set("srb:core:categoryList" + param.getParentId(), categoryList, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis服务异常");
        }
        return JsonResult.ok();
    }

    /*
    修改分类名称
     */
    public JsonResult updateCategoryName(CategoryParam param) {
        // 乐观锁判断
        Category category = categoryMapper.selectById(param.getCategoryId());
        // 判断分类名是否已经存在
        if (!checkExisted(param.getCategoryName(), category.getParentId())) {
            return JsonResult.error().message("该分类名已经存在，无法进行修改");
        }
        // 更新分类信息
        category.setCategoryName(param.getCategoryName());
        category.setCreateBy(null);
        category.setUpdateBy(null);
        category.setCreateTime(null);
        category.setUpdateTime(null);
        int i = categoryMapper.updateById(category);
        if (i == 0) {
            return JsonResult.error().message("该分类已被其他用户修改，请再次检索");
        }

        // 获取分类list
        Map<String, Object> categoryMap = new HashMap<>();
        categoryMap.put("parent_id", param.getParentId());
        List<Category> categoryList = categoryMapper.selectByMap(categoryMap);

        // 将查到的数据存入redis
        try {
            redisTemplate.opsForValue().set("srb:core:categoryList" + param.getParentId(), categoryList, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis服务异常");
        }
        return JsonResult.ok();
    }

    /*
    根据分类ID获取分类
     */
    public JsonResult updateCategory(Long categoryId) {
        Category category = categoryMapper.selectById(categoryId);
        return JsonResult.ok().data("category", category);
    }

    /*
    判断要插入/修改的分类名在该一级/二级分类中是否已经存在
     */
    private Boolean checkExisted (String categoryName, Long parentId) {
        Map<String, Object> categoryMap = new HashMap<>();
        categoryMap.put("category_name", categoryName);
        categoryMap.put("parent_id", parentId);
        List<Category> categoryList = categoryMapper.selectByMap(categoryMap);
        return CollectionUtils.isEmpty(categoryList);
    }

}
